<template>
  <div class="app-container">
    <el-tabs v-model="active_tab" @tab-click="handleTabs">
      <!-- 一. 考核项 -->
      <el-tab-pane label="考核项设置" name="first">
        <!-- 操作 -->
        <div class="crud">
          <div>
            <el-button v-if="role_list.indexOf('80000080601') != -1" class="fill-btn"
              @click="handleUpdate(-1, 'create')">新增考评项</el-button>
            <el-button v-if="role_list.indexOf('80000080603') != -1" class="plain-btn" @click="handleDelmultip">删除
            </el-button>
          </div>
          <!-- <div class="search">
            <el-input v-model="listQuery.keyword" placeholder="查找考核项" class="crud-input">
              <el-button class="search-btn" slot="append" icon="el-icon-search" @click="handleFilter" />
            </el-input>
          </div> -->
        </div>

        <!-- 一.0 table表格 -->
        <el-table :data="list" style="width: 100%; margin-bottom: 20px" row-key="id" border :default-expand-all="false"
          :tree-props="{ children: 'items' }" @selection-change="handleSelectionChange"
          :default-sort="{prop: 'createTime', order: 'descending'}">
          <el-table-column type="selection" width="55" :selectable="selectInit" />

          <el-table-column prop="name" label="考评项" sortable min-width="450px" align="left">
          </el-table-column>

          <el-table-column label="创建时间" prop="createTime" sortable min-width="130" align="center">
            <template slot-scope="{row}">
              <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="score" label="总分" width="100" sortable align="center">
          </el-table-column>

          <el-table-column label="操作" align="center" width="150px" class-name="small-padding fixed-width">
            <template v-if="role_list.indexOf('80000080602') != -1" slot-scope="{ row }">
              <span class="action action-update" @click="handleUpdate(row, 'update')" v-show="selectInit(row)">编辑</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
          @pagination="getList" />

        <!-- 一.1 编辑,添加 考评项的弹出框 -->
        <el-dialog :title="GeneralTitleOne" class="update-questions" :visible.sync="dialog_check" width="60%" center
          :close-on-click-modal="false" @close="addCancel">
          <el-form ref="dataForm" :model="temp" :rules="rules" label-width="95px" label-position="right">
            <el-row class="questions-item" :gutter="20" type="flex" align="middle">
              <el-col :span="18">
                <el-form-item prop="name">
                  <span slot="label" class="form-item-label">考评项分组</span>
                  <el-input ref="check_name" key="check_name" v-model="temp.name" placeholder="按考评项的类别分组"
                    name="check_name" type="text" tabindex="1" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                设为公用:
                <el-switch v-model="temp.isPublic" active-text="是" inactive-text="否" :active-value="1"
                  :inactive-value="0" />
              </el-col>
            </el-row>

            <el-row class="questions-item" :gutter="20" type="flex" align="middle" v-for="(option, i) in temp.items"
              :key="i" v-show="option.remove == 0">
              <el-col :span="11">
                <el-form-item label="考评项" prop="name">
                  <el-input ref="option_name" :key="'option_name' + i" v-model="option.name" placeholder="考评项"
                    name="option_name" type="text" />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="分数">
                  <!-- <el-autocomplete v-model="option.score" :fetch-suggestions="scoreQuery" placeholder="请输入分数" ></el-autocomplete> -->
                  <el-input ref="option_score" :key="'option_score' + i" v-model="option.score" maxlength="5"
                    placeholder="分数" name="option_score" type="text" />
                  <!-- <el-select  v-model="option.score" filterable reserve-keyword placeholder="分数" clearable >
                    <el-option v-for="item in list_score" :key="item.id" :label="item.label" :value="item.id" />
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <i class="el-icon-remove remove" @click="(option.remove = 1), DeleteFixed()"></i>
              </el-col>
              <el-col :span="4">
                <div class="score-btn">
                  <span class="score-btn-item" @click="handleScore(i, 10)">10</span>
                  <span class="score-btn-item" @click="handleScore(i, 20)">20</span>
                  <span class="score-btn-item" @click="handleScore(i, 30)">30</span>
                  <span class="score-btn-item" @click="handleScore(i, 40)">40</span>
                </div>
              </el-col>
            </el-row>

            <el-row class="add-more" :gutter="20" type="flex" align="middle" justify="center" @click.native="addMore">
              更多考评项 <i class="el-icon-plus arrow"></i>
            </el-row>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button class="plain-dialog-btn" @click="dialog_check = false">取消</el-button>
            <el-button class="fill-dialog-btn" @click="dialogStatus === 'create' ? createData() : updateData()">确认
            </el-button>
          </div>
        </el-dialog>

        <!-- 一.2删除的提示框 -->
        <el-dialog :visible.sync="dialogPvVisible" title="提示" width="30%" center>
          <div class="del-data del-img">
            <img :src="require('../../assets/img/del.png')" alt="" />
          </div>
          <div class="del-data del-notify">确定考评组进行【删除】？</div>
          <span slot="footer" class="dialog-footer">
            <el-button class="plain-dialog-btn" @click="dialogPvVisible = false">取消</el-button>
            <el-button class="fill-dialog-btn" @click="delData">确认</el-button>
          </span>
        </el-dialog>
        <!-- 一.3状态更改的提示框 -->
        <el-dialog :visible.sync="dialogToggle" title="提示" width="30%" center>
          <div class="del-data del-img">
            <img :src="require('../../assets/img/remind.png')" alt="" />
          </div>
          <div class="del-data del-notify">确定对状态进行【更改】？</div>
          <span slot="footer" class="dialog-footer">
            <el-button class="plain-dialog-btn">取消</el-button>
            <el-button class="fill-dialog-btn">确认</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>

      <!-- 二. 考核模板 -->
      <el-tab-pane label="考核模板" name="second">
        <!-- 操作 -->
        <div class="crud">
          <div>
            <el-button v-if="role_list.indexOf('80000080604') != -1" class="fill-btn"
              @click="handleUpdate2(-1, 'create')">新增考评模板</el-button>
            <el-button v-if="role_list.indexOf('80000080606') != -1" class="plain-btn" @click="handleDelmultip2">删除
            </el-button>
          </div>
          <!-- <div class="search">
            <el-input v-model="listQuery2.keyword" placeholder="查找考评模板" class="crud-input">
              <el-button class="search-btn" slot="append" icon="el-icon-search" @click="handleFilter2" />
            </el-input>
          </div> -->
        </div>

        <!-- 二.0 table表格 -->
        <el-table :key="tableKey2" v-loading="listLoading2" :data="list2" border fit highlight-current-row
          style="width: 100%" @selection-change="handleSelectionChange2">
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" width="55" label="序号" />
          <el-table-column label="模板名称" prop="name" sortable min-width="150" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总分" width="100" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.score }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
            <template v-if="role_list.indexOf('80000080605') != -1" slot-scope="{ row }">
              <span class="action action-update" @click="handleUpdate2(row, 'update') != -1">编辑</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total2 > 0" :total="total2" :page.sync="listQuery2.page" :limit.sync="listQuery2.limit"
          @pagination="getList2" />

        <!-- 二.1 编辑,添加的弹出框 -->
        <el-dialog :title="GeneralTitleTow" class="update-template" :visible.sync="dialog_check2" width="60%"
          :close-on-click-modal="false" center>
          <el-form ref="dataForm2" :model="temp2" :rules="rules" label-width="95px" label-position="right">
            <el-row class="template-item" :gutter="20" type="flex" align="middle">
              <el-col :span="18">
                <el-form-item prop="name">
                  <span slot="label" class="form-item-label">模板名称</span>
                  <el-input ref="check_name" key="check_name" v-model="temp2.name" placeholder="模板名称" name="check_name"
                    type="text" tabindex="1" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="设为公用: ">
                  <el-switch v-model="temp.isPublic" active-text="是" inactive-text="否" :active-value="1"
                    :inactive-value="0" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 分割线 -->
            <el-row class="qn-line" :gutter="20"></el-row>

            <el-row class="template-item" :gutter="20">
              <el-col :span="4">
                <div>关联考评项:</div>
                <div class="the-score">选中项总分值 {{ temp2.score }}</div>
              </el-col>
              <el-col :span="20">
                <el-tree :data="list" show-checkbox node-key="id" :default-checked-keys="
                    dialogStatus2 == 'update' ? temp2.check_arr : []
                  " @check-change="checkChangeNode2" @check="SelectedStatusfun" :props="defaultPorps2" ref="my_tree">
                </el-tree>
              </el-col>
            </el-row>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button class="plain-dialog-btn" @click="cancel">取消</el-button>
            <el-button class="fill-dialog-btn" @click="dialogStatus2 == 'create' ? createData2() : updateData2()">确认
            </el-button>
          </div>
        </el-dialog>
        <!-- 2删除的提示框 -->
        <el-dialog :visible.sync="dialogPvVisible2" title="提示" width="30%" center>
          <div class="del-data del-img">
            <img :src="require('../../assets/img/del.png')" alt="" />
          </div>
          <div class="del-data del-notify">确定对模板进行【删除】？</div>
          <span slot="footer" class="dialog-footer">
            <el-button class="plain-dialog-btn" @click="dialogPvVisible2 = false">取消</el-button>
            <el-button class="fill-dialog-btn" @click="delData2">确认</el-button>
          </span>
        </el-dialog>
        <!-- 3状态更改的提示框 -->
        <el-dialog :visible.sync="dialogToggle2" title="提示" width="30%" center>
          <div class="del-data del-img">
            <img :src="require('../../assets/img/remind.png')" alt="" />
          </div>
          <div class="del-data del-notify">确定对状态进行【更改】？</div>
          <span slot="footer" class="dialog-footer">
            <el-button class="plain-dialog-btn">取消</el-button>
            <el-button class="fill-dialog-btn">确认</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>

      <!-- 三. 其他设置 -->
      <el-tab-pane label="其他设置" name="third">
        <!-- 操作 -->
        <div class="crud">
          <div>
            <el-button v-if="role_list.indexOf('80000080607') != -1" class="fill-btn" @click="handleUpdate3()">新增规则
            </el-button>
            <el-button v-if="role_list.indexOf('80000080609') != -1" class="plain-btn" @click="handleDelmultip3">删除
            </el-button>
          </div>
          <!-- <div class="search">
            <el-input v-model="listQuery3.keyword" placeholder="查找考核项" class="crud-input">
              <el-button class="search-btn" slot="append" icon="el-icon-search" @click="handleFilter" />
            </el-input>
          </div> -->
        </div>

        <!-- 一.0 table表格 -->
        <el-table :key="tableKey3" v-loading="listLoading3" :data="list3" border fit highlight-current-row
          style="width: 100%" @selection-change="handleSelectionChange3">
          <el-table-column type="selection" width="55" />

          <el-table-column label="规则编号" align="center">
            <template slot-scope="{ row }">
              <div v-if="row.edit_inline" class="temp-input">
                <el-input v-model="row.code" class="edit-input" size="small" />
              </div>
              <span v-else>{{ row.code }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规则名称" align="center">
            <template slot-scope="{ row }">
              <div v-if="row.edit_inline" class="temp-input">
                <el-input v-model="row.name" class="edit-input" size="small" />
              </div>
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="具体规则" align="center">
            <template slot-scope="{ row }">
              <div v-if="row.edit_inline" class="temp-input">
                <el-input v-model="row.content" class="edit-input" size="small" />
              </div>
              <span v-else>{{ row.content }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template v-if="role_list.indexOf('80000080609') != -1" slot-scope="{ row }">
              <template v-if="row.edit_inline">
                <span v-if="row.edit_inline" class="action action-update" @click="cancelEditLine3(row)">取消</span>
                <span> | </span>
                <span v-if="row.edit_inline" class="action action-update" @click="updateDataInline3(row)">保存</span>
              </template>
              <span v-else class="action action-update" @click="row.edit_inline = !row.edit_inline">编辑</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
          @pagination="getList" />

        <!-- 三.1删除的提示框 -->
        <el-dialog :visible.sync="dialogPvVisible3" title="提示" width="30%" center>
          <div class="del-data del-img">
            <img :src="require('../../assets/img/del.png')" alt="" />
          </div>
          <div class="del-data del-notify">确定对规则进行【删除】？</div>
          <span slot="footer" class="dialog-footer">
            <el-button class="plain-dialog-btn" @click="dialogPvVisible3 = false">取消</el-button>
            <el-button class="fill-dialog-btn" @click="delData3">确认</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import waves from "@/directive/waves"; // waves directive
  import {
    parseTime
  } from "@/utils"; // 解析时间
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import {
    addCheck,
    editCheck,
    delCheck,
    listCheck,
    addTemplate,
    editTemplate,
    delTemplate,
    listTemplate,
    addRegular,
    editRegular,
    delRegular,
    listRegular,
  } from "@/api/cruising";

  import {
    validPass
  } from "@/utils/validate";
  import {
    logger
  } from "runjs/lib/common";

  const calendarTypeOptions = [{
      key: "CN",
      display_name: "China"
    },
    {
      key: "US",
      display_name: "USA"
    },
    {
      key: "JP",
      display_name: "Japan"
    },
    {
      key: "EU",
      display_name: "Eurozone"
    },
  ];

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name;
    return acc;
  }, {});

  export default {
    name: "CruSetting",
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: "success",
          draft: "info",
          deleted: "danger",
        };
        return statusMap[status];
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type];
      },
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        // if (!validPass(value) && (value && value.length != 64)) {
        if (!validPass(value)) {
          callback(new Error("8~16位,包含大小写字母和数字, 可以有特殊字符"));
        } else {
          callback();
        }
      };

      const validateRoleName = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入角色名称！"));
        } else {
          const reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
          if (value.length > 20 || !reg.test(value)) {
            callback(
              new Error("请输入1～20个字，角色名只允许中英文、数字和下划线！")
            );
          } else {
            callback();
          }
        }
      };

      const questionName = (rule, value, callback) => {
        if (value && value.length <= 56 && value.length >= 3) {
          callback();
        } else {
          callback(new Error("名称在3~56位之间"));
        }
      };
      const questionScore = (rule, value, callback) => {
        if (!/^\d{1,5}$/.test(value)) {
          callback(new Error("考评分数在1~5位之间"));
        } else {
          callback();
        }
      };

      return {
        active_tab: "first",
        rules: {
          roleName: [{
            validator: validateRoleName,
            trigger: "blur"
          }],
          password: [{
            required: true,
            trigger: "blur",
            validator: validatePassword
          }, ],
          userName: [{
            required: true,
            trigger: "blur",
            validator: validatePassword
          }, ],
          again_pass: [{
            required: true,
            trigger: "blur",
            validator: validatePassword
          }, ],
          name: [{
            required: true,
            trigger: "blur",
            validator: questionName
          }],
          score: [{
            required: true,
            trigger: "blur",
            validator: questionScore
          }],
        },

        // =======================考评项==========================
        tableKey: 0,
        listQuery: {
          page: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: "", // 搜索关键字
        },
        temp: {
          name: "", // 考评组的名字
          isPublic: 0,
          items: [{
            remove: 0,
            name: "",
            isPublic: 0,
            score: ""
          }],
        },
        dialog_check: false,
        dialogStatus: "create",
        list: [],
        total: 0, // 总条数
        listLoading: true, // tabel加载中
        multipleSelection: [], // 多选的行数据列表
        is_multip: false, // 是否批量删除
        del_id: "",
        del_index: null,
        dialogPvVisible: false, // 删除提示框
        dialogToggle: false, // 状态更改的提示框
        list_score: [{
            id: 10,
            value: "10"
          },
          {
            id: 20,
            value: "20"
          },
          {
            id: 30,
            value: "30"
          },
          {
            id: 40,
            value: "40"
          },
          {
            id: 50,
            value: "50"
          },
          {
            id: 60,
            value: "60"
          },
          {
            id: 70,
            value: "70"
          },
          {
            id: 80,
            value: "80"
          },
          {
            id: 90,
            value: "90"
          },
        ],

        // =======================考评模板=======================
        tableKey2: 2,
        listQuery2: {
          page: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: "", // 搜索关键字
        },
        temp2: {
          name: "", // 考评组的名字
          isPublic: 0,
          checkItems: "",
          check_arr: [],
          score: 0,
        },
        dialog_check2: false,
        dialogStatus2: "create",
        list2: [],
        total2: 0, // 总条数
        listLoading2: true, // tabel加载中
        multipleSelection2: [], // 多选的行数据列表
        is_multip2: false, // 是否批量删除
        del_id2: "",
        del_index2: null,
        dialogPvVisible2: false, // 删除提示框
        dialogToggle2: false, // 状态更改的提示框

        defaultPorps2: {
          // tree 配置项
          children: "items",
          label: "name",
        },
        // ============其他设置================
        tableKey3: 3,
        listQuery3: {
          page: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: "", // 搜索关键字
        },
        temp3: {
          name: "", // 考评组的名字
          isPublic: 0,
          checkItems: "",
          check_arr: [],
          score: 0,
        },
        dialog_check3: false,
        dialogStatus3: "create",
        list3: [],
        total3: 0, // 总条数
        listLoading3: true, // tabel加载中
        multipleSelection3: [], // 多选的行数据列表
        is_multip3: false, // 是否批量删除
        del_id3: "",
        del_index3: null,
        dialogPvVisible3: false, // 删除提示框
        dialogToggle3: false, // 状态更改的提示框
        add_underway: false, // 添加是否在进行当中
        SelectedStatus: "",
        current: true, // 节流变量
        GeneralTitleOne: "",
        GeneralTitleTow: "",
        role_list: [], // 按钮权限
      };
    },
    watch: {},
    created() {
      this.getList();
      this.getList2();
      this.getList3();
    },
    mounted() {
      this.role_list = this.$store.getters.menu_code_list;
    },
    methods: {
      // 判断是否还有子节点
      selectInit(row, index) {
        if (typeof row.items == "undefined") {
          return false;
        } else {
          return true;
        }
      },
      DeleteFixed() {
        // 改变key让他重新渲染
        this.temp.items.push();
      },
      // 点击tabs的某一项
      handleTabs(tab, event) {
        // console.log(tab, event);
      },
      // =======================考评组( 考评项 )===============================
      // 获取考评组列表
      getList() {
        this.listLoading = true;
        // {pageNo:this.listQuery.page, pageSize: this.listQuery.limit, name:this.listQuery.keyword}
        listCheck().then((res) => {
          if (res.code == 0) {
            this.list = res.data;
            if (this.list && this.list.length > 0) {
              this.list.forEach((val, i) => {
                val.items.map((item, i) => {
                  item.remove = 0;
                });
              });
            }
            this.total = parseInt(res.total);

            this.listLoading = false;
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        }).catch(() => {
          this.$message({
            message: "网络错误",
            type: "error",
          });
        });
      },

      // 添加更多考评项
      addMore() {
        this.temp.items.push({
          id: new Date().toString(),
          remove: 0,
          name: "",
          isPublic: 0,
          score: 0,
        });
      },
      handleScore(i, num) {
        this.temp.items[i].score = num;
      },
      // // 分数备选项
      // scoreQuery(queryString, cb) {
      //   var restaurants = this.list_score;
      //   var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      //   // 调用 callback 返回建议列表的数据
      //   cb(results);
      // },
      // //
      // createFilter(queryString) {
      //   return (restaurant) => {
      //     return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      //   };
      // },

      // 点击了 '编辑' 或 '添加'
      handleUpdate(row, str) {
        if (str == "create") {
          this.resetTemp();
          this.GeneralTitleOne = "新增考评项";
        } else if (str == "update") {
          this.GeneralTitleOne = "编辑考评项";
          this.temp = Object.assign({}, row); // 克隆一个对象
        }
        this.dialogStatus = str;
        this.dialog_check = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      },
      // 取消编辑或添加
      addCancel() {
        this.getList() // 也可通过本地存储的方式解决,或者深拷贝来解决, 中途取消更改的数据恢复问题
      },

      // 添加考评组
      createData() {
        if (this.current) {
          this.current = false;

          this.$refs["dataForm"].validate((valid) => {
            if (valid) {
              let temp_data = Object.assign({}, this.temp); // 克隆一个对象
              let temp_items;
              if (this.temp && this.temp.items.length > 0) {
                temp_items = this.temp.items.filter((item, i) => {
                  item.isPublic = this.temp.isPublic;
                  return item.remove == 0;
                });
              }
              temp_data.items = temp_items;
              addCheck(temp_data).then(() => {
                // this.list.unshift(this.temp)   // 添加成功 要获取id, (取消前端数据更新的方式)
                this.getList();
                this.dialog_check = false;
                this.$notify({
                  title: "成功",
                  message: "创建成功",
                  type: "success",
                  duration: 4000,
                });
              });
            }
          });

          setTimeout(() => {
            this.current = true;
          }, 2000);
        }
      },
      // 编辑: 确认更新数据
      updateData() {
        if (this.current) {
          this.current = false;

          this.$refs["dataForm"].validate((valid) => {
            if (valid) {
              let temp_data = Object.assign({}, this.temp); // 克隆一个对象
              let temp_items;
              if (this.temp && this.temp.items.length > 0) {
                temp_items = this.temp.items.filter((item, i) => {
                  item.isPublic = this.temp.isPublic;
                  return item.remove == 0;
                });
              }
              temp_data.items = temp_items;

              editCheck(temp_data).then(() => {
                // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
                // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
                this.getList();
                this.dialog_check = false;
                this.$notify({
                  title: "成功",
                  message: "更新成功",
                  type: "success",
                  duration: 4000,
                });
              });
            }
          });

          setTimeout(() => {
            this.current = true;
          }, 2000);
        }
      },
      // 清空temp
      resetTemp() {
        this.temp = {
          name: "", // 考评组的名字
          isPublic: 0,
          items: [{
            remove: 0,
            name: "",
            isPublic: 0,
            score: ""
          }],
        };
      },
      // 批量选择
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 单个删除
      handleDelete(row, index) {
        this.is_multip = false;
        this.del_id = row.id;
        this.del_index = index;
        this.dialogPvVisible = true;
      },
      // 批量删除
      handleDelmultip() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: "没有被选项!",
            type: "error",
            duration: 4000,
            showClose: true,
            center: true,
          });
        } else {
          this.is_multip = true;
          this.dialogPvVisible = true;
        }
      },
      // 确认了删除
      delData() {
        let ids = [];
        if (this.is_multip) {
          // 批量删
          this.multipleSelection.forEach((item, i) => {
            ids.push(item.id);
          });
        } else {
          ids = [this.del_id];
        }
        delCheck(ids).then(() => {
          this.dialogPvVisible = false;
          // this.list.splice(this.del_index, 1)
          this.getList();
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 4000,
          });
        });
      },

      // 搜索
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },

      // ===================================考评模板========================================
      // 获取考评组列表
      getList2() {
        this.listLoading2 = true;
        // {pageNo:this.listQuery.page, pageSize: this.listQuery.limit, name:this.listQuery.keyword}
        listTemplate()
          .then((res) => {
            if (res.code == 0) {
              this.list2 = res.data;
              // if(this.list2 && this.list.length > 0) {
              //   this.list2.forEach((val,i) => {
              //     val.items.map((item,i) => {
              //       item.remove = 0
              //     })
              //   })
              // }
              this.total2 = parseInt(res.total);
              this.listLoading2 = false;
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          })
          .catch(() => {
            this.$message({
              message: "网络错误",
              type: "error",
            });
          });
      },

      // 点击了 '编辑' 或 '添加'
      handleUpdate2(row, str) {
        this.dialog_check2 = true;
        if (str == "create") {
          this.$nextTick(() => {
            this.resetTemp2();
          });
          this.GeneralTitleTow = "新增考评模板";
        } else if (str == "update") {
          this.$nextTick(() => {
            this.resetTemp2();
            this.GeneralTitleTow = "编辑考评模板";
            this.temp2 = Object.assign({}, row); // 克隆一个对象
            this.temp2.check_arr = [];
            row.items.forEach((val, i) => {
              this.temp2.check_arr.push(val.id);
            });
            this.SelectedStatus = row.items.length
          });
        }
        this.dialogStatus2 = str;
        // this.dialog_check2 = true
        this.$nextTick(() => {
          this.$refs["dataForm2"].clearValidate();
        });
      },
      // 添加考评组
      createData2() {
        if (this.current) {
          this.current = false;

          this.$refs["dataForm2"].validate((valid) => {
            if (valid) {
              let temp_arr = this.$refs["my_tree"].getCheckedKeys(true);
              if (temp_arr && temp_arr.length > 0) {
                this.temp2.checkItems = temp_arr.toString();
                addTemplate(this.temp2).then(() => {
                  // this.list.unshift(this.temp)   // 添加成功 要获取id, (取消前端数据更新的方式)
                  this.getList2();
                  this.dialog_check2 = false;
                  this.$notify({
                    title: "成功",
                    message: "创建成功",
                    type: "success",
                    duration: 4000,
                  });
                });
              } else {
                this.$message({
                  message: '请选择关联考评项',
                  type: 'error',
                })
              }
            }
          });

          setTimeout(() => {
            this.current = true;
          }, 2000);
        }
      },
      // 编辑: 确认更新数据
      updateData2() {
        if (this.current) {
          this.current = false;

          this.$refs["dataForm2"].validate((valid) => {
            if (valid) {
              let temp_arr = this.$refs["my_tree"].getCheckedKeys(true);
              if (temp_arr && temp_arr.length > 0) {
                this.temp2.checkItems = temp_arr.toString();
                editTemplate(this.temp2).then(() => {
                  // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
                  // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
                  this.getList2();
                  this.dialog_check2 = false;
                  this.$notify({
                    title: "成功",
                    message: "更新成功",
                    type: "success",
                    duration: 4000,
                  });
                })
              } else {
                this.$message({
                  message: '请选择关联考评项',
                  type: 'error',
                })
              }
            }
          });

          setTimeout(() => {
            this.current = true;
          }, 2000);
        }
      },
      // 清空temp
      resetTemp2() {
        this.temp2 = {
          name: "", // 考评组的名字
          isPublic: 0,
          checkItems: "",
          check_arr: [],
          score: 0,
        };
        this.SelectedStatus = "";
        this.$refs["my_tree"].setCheckedKeys([]);
      },
      // 批量选择
      handleSelectionChange2(val) {
        this.multipleSelection2 = val;
      },
      // 单个删除
      handleDelete2(row, index) {
        this.is_multip2 = false;
        this.del_id2 = row.id;
        this.del_index2 = index;
        this.dialogPvVisible2 = true;
      },
      // 批量删除
      handleDelmultip2() {
        if (this.multipleSelection2.length == 0) {
          this.$message({
            message: "没有被选项!",
            type: "error",
            duration: 4000,
            showClose: true,
            center: true,
          });
        } else {
          this.is_multip2 = true;
          this.dialogPvVisible2 = true;
        }
      },
      // 确认了删除
      delData2() {
        let ids = [];
        if (this.is_multip2) {
          // 批量删
          this.multipleSelection2.forEach((item, i) => {
            ids.push(item.id);
          });
        } else {
          ids = [this.del_id];
        }
        delTemplate(ids).then(() => {
          this.dialogPvVisible2 = false;
          // this.list.splice(this.del_index, 1)
          this.getList2();
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 4000,
          });
        });
      },
      // 节点发生变化  ( 来获取到分数的值 )
      SelectedStatusfun(data, Select) {
        if (this.SelectedStatus < Select.checkedNodes.length) {
          // console.log('添加了 :>> ');
          this.temp2.score = this.temp2.score + data.score;
        } else {
          // console.log('减少了 :>> ');
          this.temp2.score = this.temp2.score - data.score;
        }
        this.SelectedStatus = Select.checkedNodes.length;
      },
      cancel() {
        this.dialog_check2 = false;
        this.resetTemp2();
      },
      checkChangeNode2(data, check, child_has_check) {
        let temp_node = this.$refs["my_tree"].getNode(data);

        // if (typeof(data.items) == 'undefined') {
        //   console.log('可以拿 :>> ');
        // }
        // console.log('看看参数1 :>> ', data.score);
        // console.log('看看参数2 :>> ', check);
        // console.log('看看参数3 :>> ', child_has_check);

        if (temp_node.checked && temp_node.level == 2 && temp_node.isLeaf) {
          if (this.dialogStatus2 == "update") this.temp2.check_arr.push(data.id);
        }
      },

      // 搜索
      handleFilter2() {
        this.listQuery.page = 1;
        this.getList();
      },

      // ================================其他设置(规则)==================================
      // 获取考评组列表
      getList3() {
        this.listLoading3 = true;
        listRegular()
          .then((res) => {
            if (res.code == 0) {
              this.list3 = res.data;
              this.total3 = parseInt(res.total);

              this.list3 = this.list3.map((item, i) => {
                this.$set(item, "edit_inline", false);
                item.original_name = item.name;
                item.original_code = item.code;
                item.original_content = item.content;
                return item;
              });

              setTimeout(() => {
                this.listLoading3 = false;
              }, 0.9 * 1000);
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          })
          .catch(() => {
            this.$message({
              message: "网络错误",
              type: "error",
            });
          });
      },
      // 取消当行编辑
      cancelEditLine3(row) {
        if (row.is_add) {
          this.add_underway = false;
          this.list3.pop();
        } else {
          row.name = row.original_name;
          row.code = row.original_code;
          row.content = row.original_content;
          row.edit_inline = false;
        }
        this.$message({
          message: "已经取消更改",
          type: "warning",
        });
      },
      // 点击新增规则
      handleUpdate3() {
        if (!this.add_underway) {
          this.add_underway = true;
          this.list3.push({
            name: "",
            content: "",
            code: "",
            edit_inline: true,
            is_add: true,
          });
        } else {
          this.$message({
            message: "当前新增尚未保存",
            type: "error",
          });
        }
      },

      // 行内修改 或 新增
      updateDataInline3(row) {
        // 节流
        if (this.current) {
          this.current = false;

          if (row.is_add) {
            addRegular(row).then(() => {
              // this.list.unshift(this.temp)   // 添加成功 要获取id, (取消前端数据更新的方式)
              this.add_underway = false;
              this.getList3();
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
                duration: 4000,
              });
            });
          } else {
            editRegular(row).then(() => {
              // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
              // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
              // this.getList3()
              row.edit_inline = false;
              this.$notify({
                title: "成功",
                message: "更新成功",
                type: "success",
                duration: 4000,
              });
            });
          }

          setTimeout(() => {
            this.current = true;
          }, 1000);
        }
      },

      // 批量选择
      handleSelectionChange3(val) {
        this.multipleSelection3 = val;
      },
      // 单个删除
      handleDelete3(row, index) {
        this.is_multip3 = false;
        this.del_id3 = row.id;
        this.del_index3 = index;
        this.dialogPvVisible3 = true;
      },
      // 批量删除
      handleDelmultip3() {
        if (this.multipleSelection3.length == 0) {
          this.$message({
            message: "没有被选项!",
            type: "error",
            duration: 4000,
            showClose: true,
            center: true,
          });
        } else {
          this.is_multip3 = true;
          this.dialogPvVisible3 = true;
        }
      },
      // 确认了删除
      delData3() {
        let ids = [];
        if (this.is_multip3) {
          // 批量删
          this.multipleSelection3.forEach((item, i) => {
            ids.push(item.id);
          });
        } else {
          ids = [this.del_id];
        }
        delRegular(ids).then(() => {
          this.dialogPvVisible3 = false;
          // this.list.splice(this.del_index, 1)
          this.getList3();
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 4000,
          });
        });
      },
    },
  };
</script>

<style lang="scss">
  @import "~@/styles/variables.scss";

  .crud-input {
    border: 0;

    &.el-input--medium {
      font-size: 12px;
    }

    &.el-input--medium .el-input__inner {
      height: 27px !important;
      background: transparent;
      border: 0;
      -webkit-appearance: none;
      border-radius: 3px;
      // padding: 12px 5px 12px 15px;
      color: $text_dark;
      caret-color: $text_dark;

      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px $my_opacity inset !important;
        -webkit-text-fill-color: $text_dark !important;
      }
    }

    .el-input-group__append {
      color: $my-primary;
      border: 0;
      border-left: 1px solid $my-primary;

      .el-button {
        // height: 27px;
        // border: 1px solid $my-primary !important;
        // background-color: #f11;
      }
    }
  }

  .el-dialog {
    .el-dialog__header {
      background-color: #f5f7f5 !important;
    }
  }

  .qn-role-textarea {
    .el-textarea__inner {
      height: 70px;
      font-size: 14px;
      font-weight: 400;
      background: rgba(0, 0, 0, 0.02);
      border: 1px dashed rgba(0, 0, 0, 0.15);
      border-radius: 4px;
    }
  }

  // 输入框外边距: 底部
  .app-container {
    .update-questions {
      .el-form {
        .el-form-item {
          margin-bottom: 0;
        }
      }
    }
  }

  .el-form-item__label {
    // 两端对齐
    display: flex;
    justify-content: space-between;
    align-items: center !important;

    &::before {
      // line-height: 30px;
      transform: translateY(3px);
    }

    .form-item-label {
      flex: 1;
      text-align-last: justify !important;
      text-align: justify !important;
    }
  }
</style>


<style lang="scss" scoped>
  @import "~@/styles/variables.scss";

  .app-container {
    padding: 10px;
    background-color: #ffffff;

    .crud {
      margin-bottom: 32px;
      display: flex;
      justify-content: space-between;

      .crud-input {
        height: 27px;
        width: 300px;
        border: 1px solid $my-primary;
        border-radius: 3px;
        // background-color: aqua;
      }
    }

    .el-table {
      .action {
        font-size: 13px;
        color: $my-primary;
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }

      .expand-row {
        line-height: 28px;

        // background-color: rgb(187, 87, 81);
        &.bdbom {
          border-bottom: 1px dashed $border_light;
        }
      }
    }

    .el-dialog {
      .del-data {
        text-align: center;
        margin-bottom: 16px;

        img {
          width: 130px;
          height: 110px;
        }
      }

      .del-img {}
    }

    // 编辑考评组
    .update-questions {
      .questions-item {
        margin-bottom: 20px;

        .remove {
          color: $my-danger;
          font-size: 22px;
          cursor: pointer;
        }

        .score-btn {
          .score-btn-item {
            border: 1px solid var(--app_primary);
            cursor: pointer;
            color: var(--app_primary);
            margin-right: 5px;
            padding: 2px 2px;

            &:hover {
              background-color: var(--app_primary);
              color: $my_white;
            }
          }
        }
      }

      .add-more {
        margin-top: 20px;
        height: 30px;
        background-color: rgba($color: #f0f0f0, $alpha: 0.3);
        cursor: pointer;

        &:hover {
          background-color: rgba($color: #f0f0f0, $alpha: 1);
        }

        .arrow {
          margin-left: 5px;
          // transform: rotateZ(90deg);
        }
      }
    }

    // 考评模板
    .update-template {
      .template-item {
        // background-color: #fcd;
        margin-bottom: 20px;
      }

      .qn-line {
        height: 1px;
        background-color: $border_light;
        margin-bottom: 20px;
      }

      .the-score {
        margin-top: 10px;
        color: $text_middle;
        font-size: 12px;
      }
    }
  }
</style>
